<?php
require_once 'includes/auth.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
    $password = filter_input(INPUT_POST, 'password', FILTER_UNSAFE_RAW);

    if (login_user($username, $password)) {
        $redirect = $_POST['redirect'] ?? '';

        switch ($_SESSION['user_role']) {
            case 'admin':
                header('Location: admin/'.($redirect ? "?redirect=$redirect" : ''));
                break;
            case 'data_admin':
                header('Location: sync/');
                break;
            default:
                header('Location: front/');
        }
        exit();
    } else {
        $error = "用户名或密码错误";
    }
}

// 登出逻辑
if (isset($_GET['logout'])) {
    logout_user();
    header('Location: login.php');
    exit();
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据平台 - 登录</title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/theme.css">
</head>
<body class="login-body">
<div class="login-container">
    <div class="login-card">
        <img src="assets/images/logo.png" alt="平台Logo" class="login-logo">

        <?php if (isset($error)): ?>
            <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <form method="post" class="login-form">
            <input type="hidden" name="redirect" value="<?= $_GET['redirect'] ?? '' ?>">

            <div class="mb-3">
                <label for="username" class="form-label">用户名</label>
                <input type="text" class="form-control" id="username" name="username" required autofocus>
            </div>

            <div class="mb-4">
                <label for="password" class="form-label">密码</label>
                <input type="password" class="form-control" id="password" name="password" required>
            </div>

            <button type="submit" class="btn btn-primary w-100">登录</button>
        </form>
    </div>
</div>

<script src="assets/js/bootstrap.bundle.min.js"></script>
<script src="assets/js/login-validation.js"></script>
</body>
</html>